package com.lu.project.controller;



import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.lu.project.common.BaseResponse;
import com.lu.project.common.ResultUtils;
import com.lu.project.exception.BusinessException;
import com.lu.project.exception.ErrorCode;
import com.lu.project.exception.ThrowUtils;
import com.lu.project.model.dto.ai.AIChatRequest;
import com.lu.project.model.dto.ai.AIModel;
import com.lu.project.model.dto.ai.Messages;
import com.lu.project.model.vo.ai.AIChatResponseBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Ai调用的接口 Controller
 */
@RestController
@RequestMapping("/chat")
@Api(tags = "AI调用接口")
@Slf4j
public class AiChatController {


    private final String AI_CHAT_URL = "https://api.milorapart.top/api/AIchat";
    /**
     * 新增消息待办关联记录
     *
     * @return 操作结果
     */
    @PostMapping()
    @ApiOperation(value = "输入问题聊天")
    public BaseResponse chat(@RequestParam @Validated String Content,String Model) {
        //String AI_CHAT_URL = "https://api.milorapart.top/api/AIchat";
        AIChatRequest aiChatRequest = new AIChatRequest();
        if (Model==null){
           Model = AIModel.GPT_4O_MINI.getModelName();
        }
        ThrowUtils.throwIf(Content==null,ErrorCode.PARAMS_ERROR,"请输入问题");
        Messages messages = new Messages();
        messages.setRole("admin");
        messages.setContent(Content);
        Messages[] arr = {messages};
        aiChatRequest.setMessages(arr);
        aiChatRequest.setModel(Model);
        HttpRequest httpRequest = HttpRequest.post(AI_CHAT_URL)
                .body(JSONUtil.toJsonStr(aiChatRequest));

        //System.out.println(JSONUtil.toJsonStr(aiChatRequest));
        try (HttpResponse httpResponse = httpRequest.execute()) {
            if (!httpResponse.isOk()) {
                log.error("请求异常：{}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI响应失败,请重试");
            }
            AIChatResponseBody bean = JSONUtil.toBean(httpResponse.body(), AIChatResponseBody.class);
            AIChatResponseBody.Choices choice = bean.getChoices()[0];
            String content = choice.getMessage().getContent();

            String s = formatText(content);

            return ResultUtils.success(s,"AI响应成功");
        }catch (Exception e){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"AI响应失败，请重试");
        }

    }

   /* public static void main(String[] args) {
        AIChatRequest aiChatRequest = new AIChatRequest();
        Messages messages = new Messages();
        messages.setContent("请用中文回答，仅有简单分析回答鲁迅和周树人关系");
        messages.setRole("user");
        Messages[] msgArr = {messages};
        aiChatRequest.setModel("gpt-4o-mini");
        aiChatRequest.setStream(false);
        aiChatRequest.setMessages(msgArr);
        BaseResponse<AIChatResponseBody> chat = chat(aiChatRequest);
        System.out.println(Arrays.toString(chat.getData().getChoices()));
    }*/
   public static String formatText(String text) {
       // 1. 去除Markdown标记，如 ​**
       String cleanedText = removeMarkdown(text);

       // 2. 格式化编号列表
       cleanedText = formatNumberedLists(cleanedText);

       // 3. 添加适当的段落分隔和缩进（可根据需要调整）
       cleanedText = addParagraphFormatting(cleanedText);

       return cleanedText;
   }

    /**
     * 去除Markdown格式标记
     *
     * @param text 输入文本
     * @return 去除标记后的文本
     */
    private static String removeMarkdown(String text) {
        // 去除 ​**​ 粗体
        String noBold = text.replaceAll("\\*\\*", "");
        // 可以在这里添加更多的Markdown标记去除规则，如 *斜体*，~~删除线~~ 等
        return noBold;
    }

    /**
     * 格式化编号列表，统一编号样式
     *
     * @param text 输入文本
     * @return 格式化后的文本
     */
    private static String formatNumberedLists(String text) {
        // 使用正则表达式匹配编号列表，如 "1. ", "2. ", 等
        Pattern pattern = Pattern.compile("^(\\d+)\\.\\s*(.*)$", Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(text);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String number = matcher.group(1);
            String content = matcher.group(2).trim();
            // 统一格式化为 "1. 内容" 或其他样式，如 "- 内容"
            // 这里保持数字编号，可以根据需要调整
            matcher.appendReplacement(sb, Matcher.quoteReplacement(String.format("%d. %s\n", Integer.parseInt(number), content)));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 添加段落分隔和缩进
     *
     * @param text 输入文本
     * @return 格式化后的文本
     */
    private static String addParagraphFormatting(String text) {
        // 在段落之间添加两个换行符
        String withNewlines = text.replaceAll("(\\n)\\s*(\\n)", "$1$2"); // 保留单个换行
        withNewlines = withNewlines.replaceAll("(?<!\\n)\\n(?!\n)", "\n\n"); // 确保段落之间有两个换行

        // 可选：为每个段落添加缩进
        // 这里选择不缩进，保持原样。如果需要缩进，可以使用如下代码：
        // String indentedText = withNewlines.replaceAll("(?m)^", "    "); // 每行开头添加四个空格

        return withNewlines;
    }
}
